package net.lahuobao.mall.controller.admin;

import net.lahuobao.export.util.ExportFileUtil;
import net.lahuobao.mall.entity.admin.MallEcardRebateEntity;
import net.lahuobao.mall.entity.admin.MallEcardRebateOrderEntity;
import net.lahuobao.mall.entity.admin.MallOrderEntity;
import net.lahuobao.mall.entity.admin.MallOrderdetailEntity;
import net.lahuobao.mall.entity.admin.querymodel.MallEcardRebateModel;
import net.lahuobao.mall.entity.finance.MallCarriersExpenditureAccount;
import net.lahuobao.mall.service.admin.MallEcardRebateOrderServiceI;
import net.lahuobao.mall.service.admin.MallEcardRebateServiceI;
import net.lahuobao.mall.service.admin.MallorderServiceI;
import org.apache.log4j.Logger;
import org.hibernate.sql.JoinType;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * @Description: E卡返点
 * @author zhangdaihao
 * @date 2016-12-27 17:34:53
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/mallEcardRebateController")
public class MallEcardRebateController extends BaseController {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(MallEcardRebateController.class);

    @Autowired
    private MallEcardRebateServiceI mallEcardRebateService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private MallorderServiceI orderService;

    @Resource
    private ExportFileUtil exportFileUtil;

    @Autowired
    private MallEcardRebateOrderServiceI ecardRebateOrderService;

    /**
     * 订单 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "orderlist")
    public ModelAndView orderlist(HttpServletRequest request) {
        return new ModelAndView("net/lahuobao/mall/admin/mallEcardRebateOrderList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "orderdatagrid")
    public void orderDatagrid(MallOrderEntity mallOrderEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        if(StringUtil.isNotEmpty(request.getParameter("createtime_begin"))
                && StringUtil.isNotEmpty(request.getParameter("createtime_end"))){
            mallOrderEntity.setCreateStartTime(request.getParameter("createtime_begin"));
            mallOrderEntity.setCreateEndTime(request.getParameter("createtime_end"));
        }
        TagUtil.datagrid(response, pageDateGrid(orderService.selectEcardRebateOrder(mallOrderEntity), dataGrid));
    }


    /**
     * 订单 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "orderdetailview")
    public ModelAndView orderlist(String  orderIds) {
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/mallEcardRebate");
        String[] orderIdsArray = orderIds.split(",");
        Integer[] param = new Integer[orderIdsArray.length];
        for(int i = 0; i < orderIdsArray.length; i++){
            param[i] = Integer.parseInt(orderIdsArray[i]);
        }
        Map<MallOrderEntity, List<MallOrderdetailEntity>> orderDetail = mallEcardRebateService.selectOrderDetailByOrderIds(param);
        mv.addObject("orderDetail", orderDetail);
        mv.addObject("orderIds", orderIds);
        return mv;
    }

    /**
     * E卡返点列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView("net/lahuobao/mall/admin/mallEcardRebateList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(MallEcardRebateModel query,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        //输出dataggrid
        TagUtil.datagrid(response, pageDateGrid(selectRebateListByquery(request, query), dataGrid));
		/*CriteriaQuery cq = new CriteriaQuery(MallEcardRebateEntity.class, dataGrid);
		cq.createAlias("rebateUser", "rebateUser", JoinType.LEFT_OUTER_JOIN);
		cq.createAlias("returnUser", "returnUser", JoinType.LEFT_OUTER_JOIN);
		//查询条件组装器
        //返点人
		if(StringUtil.isNotEmpty(request.getParameter("rebateUserName"))){
			cq.like("rebateUser.userName", "%"+request.getParameter("rebateUserName")+"%");
		}
        //退回人
		if(StringUtil.isNotEmpty(request.getParameter("returnUserName"))){
			cq.like("returnUser.userName", "%"+request.getParameter("returnUserName")+"%");
		}
        //返点类型
		if(StringUtil.isNotEmpty(mallEcardRebate.getRebatetype())){
			cq.eq("rebatetype", mallEcardRebate.getRebatetype());
			mallEcardRebate.setRebatetype(null);
		}
        //状态
		if(StringUtil.isNotEmpty(mallEcardRebate.getState())){
			cq.eq("state", mallEcardRebate.getState());
			mallEcardRebate.setState(null);
		}
        //返点复核状态
		if(StringUtil.isNotEmpty(mallEcardRebate.getRebateauditstate())){
			cq.eq("rebateauditstate", mallEcardRebate.getRebateauditstate());
			mallEcardRebate.setRebateauditstate(null);
		}
        //退回复核状态
		if(StringUtil.isNotEmpty(mallEcardRebate.getReturnauditstate())){
			cq.eq("returnauditstate", mallEcardRebate.getReturnauditstate());
			mallEcardRebate.setReturnauditstate(null);
		}

		cq.addOrder("rebatetime", SortDirection.desc);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallEcardRebate, request.getParameterMap());
		this.mallEcardRebateService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);*/
    }

    /**
     * 查询数据
     *
     * @param query
     * @param request
     * @return
     */
    private List<MallEcardRebateModel> selectRebateListByquery(HttpServletRequest request, MallEcardRebateModel query) {

        //获取退回时间范围
        String rebateTimeStart = request.getParameter("rebatetime_begin");
        String rebateTimeEnd = request.getParameter("rebatetime_end");
        if (StringUtil.isNotEmpty(rebateTimeStart)) {
            query.setRebateTimeStart(rebateTimeStart);
        }
        if (StringUtil.isNotEmpty(rebateTimeEnd)) {
            query.setRebateTimeEnd(rebateTimeEnd);
        }
        //获取退回时间范围
        String returnStartTime = request.getParameter("returntime_begin");
        String returnEndTime = request.getParameter("returntime_end");

        if (StringUtil.isNotEmpty(returnStartTime)) {
            query.setReturnTimeStart(returnStartTime);
        }
        if (StringUtil.isNotEmpty(returnEndTime)) {
            query.setReturnTimeEnd(returnEndTime);
        }
        return mallEcardRebateService.selectRebateListByquery(query);

    }

    /**
     * 添加或更新E卡返点
     * @param
     * @return
     */
    @RequestMapping(params = "rebate")
    @ResponseBody
    public AjaxJson save(MallEcardRebateEntity mallEcardRebate,String orderIds, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            HttpSession session = ContextHolderUtils.getSession();
            TSUser user = (TSUser)session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
            mallEcardRebate.setRebateoperator(user.getId());
            j = mallEcardRebateService.rebate(mallEcardRebate, orderIds);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("系统异常，请稍候再试！");
            e.printStackTrace();
            systemService.addLog(e.getMessage(), Globals.Log_Type_INSERT, Globals.Log_Leavel_ERROR);
        } finally {
            return j;
        }
    }


    /**
     *e卡返点退回页面和详情页面
     * @param
     * @return
     */
    @RequestMapping(params = "rebatereturnview")
    public ModelAndView rebateReturnView(Integer id, String islook) {
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/mallEcardRebateReturn");
        //查询e卡返点信息
        MallEcardRebateEntity rebateEntity = mallEcardRebateService.getEntity(MallEcardRebateEntity.class, id);
        Map<MallOrderEntity, List<MallOrderdetailEntity>> orderDetail = mallEcardRebateService.selectOrderDetailById(id);
        mv.addObject("orderDetail", orderDetail);
        mv.addObject("rebate", rebateEntity);
        mv.addObject("islook", islook);
        return mv;
    }


    /**
     *e卡返点退回
     * @param
     * @return
     */
    @RequestMapping(params = "rebatereturn")
    @ResponseBody
    public AjaxJson rebateReturn(MallEcardRebateEntity mallEcardRebate, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            HttpSession session = ContextHolderUtils.getSession();
            TSUser user = (TSUser)session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
            mallEcardRebate.setReturnoperator(user.getId());
            j = mallEcardRebateService.rebateReturn(mallEcardRebate);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("系统异常，请稍候再试!");
            e.printStackTrace();
            systemService.addLog(e.getMessage(), Globals.Log_Type_INSERT, Globals.Log_Leavel_ERROR);
        } finally {
            return j;
        }
    }

    @RequestMapping(params = "export")
    public void middleExpenditureExport(MallEcardRebateModel query, HttpServletRequest request, HttpServletResponse response,
                                        DataGrid dataGrid){
        exportFileUtil.setFileName("历史返点记录", "xlsx");
        // 构造数据导出
        try {
            int page = 1;
            int rows = 1000;
            exportFileUtil.initExport(response);
            request.setAttribute("pageExport", "yes");
            request.setAttribute("page", page);
            request.setAttribute("rows", rows);
            int begin_ = exportFileUtil.exportIOStream(response, selectExpenDateByquery(request, query, dataGrid) , rows, page, 0);
            for(int i = 2; begin_ != page; i++ ){
                page = begin_;
                request.setAttribute("page", i);
                begin_ = exportFileUtil.exportIOStream(response, selectExpenDateByquery(request, query, dataGrid), rows, begin_, 1);
            }
            exportFileUtil.finish(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询导出数据
     * @param query
     * @param request
     * @param dataGrid
     */
    public List<MallEcardRebateModel> selectExpenDateByquery(HttpServletRequest request, MallEcardRebateModel  query, DataGrid dataGrid) {
        return  this.selectRebateListByquery(request, query);
		/*CriteriaQuery cq = new CriteriaQuery(MallEcardRebateEntity.class, dataGrid);
		cq.createAlias("rebateUser", "rebateUser", JoinType.LEFT_OUTER_JOIN);
		cq.createAlias("returnUser", "returnUser", JoinType.LEFT_OUTER_JOIN);
		if(StringUtil.isNotEmpty(request.getParameter("rebateUserName"))){
			cq.like("rebateUser.userName", "%"+request.getParameter("rebateUserName")+"%");
		}

		if(StringUtil.isNotEmpty(request.getParameter("returnUserName"))){
			cq.like("returnUser.userName", "%"+request.getParameter("returnUserName")+"%");
		}

		if(StringUtil.isNotEmpty(mallEcardRebate.getRebatetype())){
			cq.eq("rebatetype", mallEcardRebate.getRebatetype());
			mallEcardRebate.setRebatetype(null);
		}

		if(StringUtil.isNotEmpty(mallEcardRebate.getState())){
			cq.eq("state", mallEcardRebate.getState());
			mallEcardRebate.setState(null);
		}
		cq.addOrder("rebatetime", SortDirection.desc);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallEcardRebate, request.getParameterMap());
		return this.mallEcardRebateService.getDataGridReturn(cq, false).getRows();*/
    }


    /**
     * E卡返点复核列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "rebatereviewlist")
    public ModelAndView rebateReviewList(HttpServletRequest request) {
        return new ModelAndView("net/lahuobao/mall/admin/mallEcardRebateReviewList");
    }

    /**
     * E卡返点复核数据
     * easyui AJAX请求数据
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */
    @RequestMapping(params = "rebatereviewdatagrid")
    public void rebateReviewDatagrid(MallEcardRebateEntity mallEcardRebate,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(MallEcardRebateEntity.class, dataGrid);
        cq.createAlias("rebateUser", "rebateUser", JoinType.LEFT_OUTER_JOIN);
        cq.createAlias("returnUser", "returnUser", JoinType.LEFT_OUTER_JOIN);
        //查询条件组装器
        //返点人
        if(StringUtil.isNotEmpty(request.getParameter("rebateUserName"))){
            cq.like("rebateUser.userName", "%"+request.getParameter("rebateUserName")+"%");
        }
        //返点类型
        if(StringUtil.isNotEmpty(mallEcardRebate.getRebatetype())){
            cq.eq("rebatetype", mallEcardRebate.getRebatetype());
            mallEcardRebate.setRebatetype(null);
        }
        //返点复核状态
        if(StringUtil.isNotEmpty(mallEcardRebate.getRebateauditstate())){
            cq.eq("rebateauditstate", mallEcardRebate.getRebateauditstate());
            mallEcardRebate.setRebateauditstate(null);
        }
        //状态为返点
        cq.eq("state", 0);
        cq.addOrder("rebatetime", SortDirection.desc);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallEcardRebate, request.getParameterMap());
        this.mallEcardRebateService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * E卡返点退回复核列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "returnreviewlist")
    public ModelAndView returnReviewList(HttpServletRequest request) {
        return new ModelAndView("net/lahuobao/mall/admin/mallEcardReturnReviewList");
    }

    /**
     * E卡返点复核数据
     * easyui AJAX请求数据
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */
    @RequestMapping(params = "returnreviewdatagrid")
    public void returnReviewDatagrid(MallEcardRebateEntity mallEcardRebate,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(MallEcardRebateEntity.class, dataGrid);
        cq.createAlias("rebateUser", "rebateUser", JoinType.LEFT_OUTER_JOIN);
        cq.createAlias("returnUser", "returnUser", JoinType.LEFT_OUTER_JOIN);
        //查询条件组装器
        //退回操作人
        if(StringUtil.isNotEmpty(request.getParameter("returnUserName"))){
            cq.like("returnUser.userName", "%"+request.getParameter("returnUserName")+"%");
        }
        //返点类型
        if(StringUtil.isNotEmpty(mallEcardRebate.getRebatetype())){
            cq.eq("rebatetype", mallEcardRebate.getRebatetype());
            mallEcardRebate.setRebatetype(null);
        }
        //退回复核状态
        if(StringUtil.isNotEmpty(mallEcardRebate.getReturnauditstate())){
            cq.eq("returnauditstate", mallEcardRebate.getReturnauditstate());
            mallEcardRebate.setReturnauditstate(null);
        }
        //状态为返点
        cq.notEq("state", 0);
        cq.addOrder("rebatetime", SortDirection.desc);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallEcardRebate, request.getParameterMap());
        this.mallEcardRebateService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * e卡返点审核页面，退回审核页面
     * @param
     * @return
     */
    @RequestMapping(params = "auditview")
    public ModelAndView auditView(Integer id) {
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/mallEcardAuditView");
        //查询e卡返点信息
        MallEcardRebateEntity rebateEntity = mallEcardRebateService.getEntity(MallEcardRebateEntity.class, id);
        Map<MallOrderEntity, List<MallOrderdetailEntity>> orderDetail = mallEcardRebateService.selectOrderDetailById(id);
        mv.addObject("orderDetail", orderDetail);
        mv.addObject("rebate", rebateEntity);
        return mv;
    }

    /**
     *e卡返点退回审核
     * @param
     * @return
     */
    @RequestMapping(params = "audit")
    @ResponseBody
    public AjaxJson audit(MallEcardRebateEntity mallEcardRebate, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            j = mallEcardRebateService.audit(mallEcardRebate);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("系统异常，请稍候再试!");
            e.printStackTrace();
            systemService.addLog(e.getMessage(), Globals.Log_Type_INSERT, Globals.Log_Leavel_ERROR);
        } finally {
            return j;
        }
    }


    /**
     * 再次返点
     *
     * @return
     */
    @RequestMapping(params = "againrebate")
    public ModelAndView againRebate(String  rebateId) {
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/mallEcardRebate");
        MallEcardRebateEntity rebateEntity = mallEcardRebateService.get(MallEcardRebateEntity.class, Integer.valueOf(rebateId));
        List<MallEcardRebateOrderEntity>  mallEcardRebateOrderEntities = ecardRebateOrderService.selectByEcardRebateId(Integer.valueOf(rebateId));
        Integer[] orderIds = new Integer[mallEcardRebateOrderEntities.size()];
        String orderIdsStr = "";
        for(int i = 0; i < mallEcardRebateOrderEntities.size(); i++){
            if(i == mallEcardRebateOrderEntities.size() - 1 ){
                orderIdsStr = orderIdsStr + mallEcardRebateOrderEntities.get(i).getOrderid()+"";
            }else{
                orderIdsStr = orderIdsStr + mallEcardRebateOrderEntities.get(i).getOrderid()+",";
            }
            orderIds[i] = mallEcardRebateOrderEntities.get(i).getOrderid();
        }
        Map<MallOrderEntity, List<MallOrderdetailEntity>> orderDetail = mallEcardRebateService.selectOrderDetailByOrderIds(orderIds);
        mv.addObject("orderDetail", orderDetail);
        mv.addObject("orderIds", orderIdsStr);
        mv.addObject("rebateEntity", rebateEntity);
        return mv;
    }
}
